﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using JuCheap.Core.Data;
using JuCheap.Core.Models.ViewModels;
using JuCheap.Core.Services.AppServices;
using Microsoft.Extensions.DependencyInjection;

namespace JuCheap.Core.Services
{
    public static class AutoMapperConfigurationCreationExtensions
    {
        public static void CreateMappings(this IServiceProvider serviceProvider)
        {
            var config = new MapperConfiguration(configurationExpression =>
            {
                var maps = FindAllConventionTypes();
                foreach (var keyValuePair in maps)
                {
                    configurationExpression.CreateMap(keyValuePair.Key, keyValuePair.Value, MemberList.None);
                    configurationExpression.CreateMap(keyValuePair.Value, keyValuePair.Key, MemberList.None);
                }
            });

            using (var scope = serviceProvider.CreateScope())
            {
                scope.ServiceProvider.GetRequiredService<IMapperAccesstor>().Mapper = config.CreateMapper();
            }
            
        }

        private static List<KeyValuePair<Type, Type>> FindAllConventionTypes()
        {
            var types = typeof(JuCheapContext).Assembly
                .ExportedTypes
                .Where(t => t.Namespace.EndsWith("Entity"))
                .ToList();

            var views = typeof(CompanyViewModel).Assembly
                .ExportedTypes
                .Where(t => t.Name.EndsWith("ViewModel"))
                .ToList();

            var result = new List<KeyValuePair<Type, Type>>();

            foreach (var model in types)
            {
                var view = views.Find(t => t.Name.StartsWith(model.Name));
                if (view != null)
                {
                    result.Add(KeyValuePair.Create(view, model));
                }
            }

            return result;
        }
    }
}
